﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using Daco.Web.UI;

namespace Daco.Web.Masters
{
    public class DACOMaster : UserControl
    {
        private Daco.Web.UI.SitePage _currentPage = null;
        public Daco.Web.UI.SitePage CurrentPage
        {
            get { return _currentPage; }
            protected set { _currentPage = value; }
        }

        private DACOHeader _header = null;
        public DACOHeader Header
        {
            get { return _header; }
            protected set { _header = value; }
        }

        private DACOFooter _footer = null;
        public DACOFooter Footer
        {
            get { return _footer; }
            protected set { _footer = value; }
        }

        private DACONavigator _navigator = null;
        public DACONavigator Navigator
        {
            get { return _navigator; }
            protected set { _navigator = value; }
        }

        private DACOBody _body = null;
        public DACOBody Body
        {
            get { return _body; }
            protected set { _body = value; }
        }

        public DACOMaster()
        {
            Header = new DACOHeader();
            Navigator = new DACONavigator();
            Body = new DACOBody();
            Footer = new DACOFooter();

            this.Init += new EventHandler(DACOMaster_Init);
            //this.Load += new EventHandler(DACOMaster_Load);
            this.Unload += new EventHandler(DACOMaster_Unload);
        }

        void DACOMaster_Init(object sender, EventArgs e)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "InitScript", @"
                    var IEBrowser = navigator.appName.indexOf(""Microsoft"") > -1;
                    function addEvent(obj, evType, fn)
                    {
                        if (obj.addEventListener) {
                            obj.addEventListener(evType, fn, true);
                            return true;
                        } else if (obj.attachEvent) {
                            var r = obj.attachEvent(""on"" + evType, fn);
                            return r;
                        } else {
                            return false;
                        }
                    }", true);

            Page.ClientScript.RegisterClientScriptInclude("JQuery", Page.ResolveUrl("~/Scripts/jquery-1.4.2.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Core", Page.ResolveUrl("~/Scripts/jquery.ui.core.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Widget", Page.ResolveUrl("~/Scripts/jquery.ui.widget.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Position", Page.ResolveUrl("~/Scripts/jquery.ui.position.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Mouse", Page.ResolveUrl("~/Scripts/jquery.ui.mouse.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Resizable", Page.ResolveUrl("~/Scripts/jquery.ui.resizable.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("JQuery.UI.Dialog", Page.ResolveUrl("~/Scripts/jquery.ui.dialog.min.js"));
            Page.ClientScript.RegisterClientScriptInclude("Utils", Page.ResolveUrl("~/Scripts/Utils.js"));
        }

        void DACOMaster_Load(object sender, EventArgs e)
        {
            // get the current page...
            string pageSrc = GetPageSource();

            try
            {
                Daco.Web.UI.SitePage currentPage = (Daco.Web.UI.SitePage)Page.LoadControl(pageSrc);

                if (currentPage.Permission.SelectAccess)
                {
                    CurrentPage = currentPage;
                    CurrentPage.Header = Header;
                    CurrentPage.Footer = Footer;
                    CurrentPage.Navigator = Navigator;

                    #region "Bind HOME Template"
                    //Web.UI.WebControls.ULTree categoryTree = new UI.WebControls.ULTree();
                    //categoryTree.DataSource = Daco.Web.Store.CProductCategory.CreateTree();
                    //categoryTree.DataBind();

                    //Web.UI.WebControls.ULTree manufactureTree = new UI.WebControls.ULTree();
                    //manufactureTree.DataSource = Daco.Web.Store.CProduct.CreateManufactureTree();
                    //manufactureTree.DataBind();
                    #endregion

                    //Body.Left.Controls.Add(categoryTree);
                    //Body.Left.Controls.Add(manufactureTree);
                    Body.Right.Controls.Add(CurrentPage);

                    CPageContext.Current.CurrentPage = CurrentPage;

                    // add the header control before the page rendering...
                    Controls.AddAt(0, Header);
                    Controls.AddAt(1, Navigator);
                    // add the page before the page rendering...
                    Controls.Add(Body);
                    // add the footer control after the page...
                    Controls.Add(Footer);
                }
                else
                {
                    // Phat sinh permission exception, thong bao ko du tham quyen de truy cap vao tai nguyen nay
                    throw new System.UnauthorizedAccessException(Daco.Web.Resources.DException.DeniedSelect);
                }
            }
            catch (System.IO.FileNotFoundException)
            {
                // Phat sinh application exception, thong bao tai nguyen truy xuat khong ton tai hoac khong co tham quyen
                throw new ApplicationException(Daco.Web.Resources.DACO.ResourceNotFound);
            }
        }

        void DACOMaster_Unload(object sender, EventArgs e)
        {
            // make sure the DacoContext is disposed of...
            Daco.Web.CPageContext.Current.Dispose();
        }

        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            writer.WriteLine(
                @"<div>
                    <div style=""margin: 0 auto; width: 1000px; background-color: white;"">");

            base.Render(writer);

            writer.WriteLine(
                @"
                    </div>
                </div>
            ");
            
            // Google tracking
//            writer.Write(@"
//                <script type=""text/javascript"">
//
//                  var _gaq = _gaq || [];
//                  _gaq.push(['_setAccount', 'UA-1132304-12']);
//                  _gaq.push(['_setDomainName', '.dacovn.com']);
//                  _gaq.push(['_trackPageview']);
//
//                  (function() {
//                    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
//                    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
//                    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
//                  })();
//
//                </script>
//            ");
        }

        protected virtual string GetPageSource()
        {
            string mod = string.IsNullOrEmpty(Request.QueryString["mod"]) ? string.Empty : Request.QueryString["mod"];
            string pag = string.IsNullOrEmpty(Request.QueryString["pag"]) ? "Home" : Request.QueryString["pag"];

            if (string.IsNullOrEmpty(mod))
                return string.Format("~/Pages/{0}.ascx", pag);
            else
                return string.Format("~/Pages/{0}/{1}.ascx", mod, pag);
        }

        protected static void CheckRequestValidity(System.Web.HttpRequest request)
        {
            // ip with 
            // deny access if POST request comes from other server
            if (request.HttpMethod == "POST" && request.UrlReferrer != null && request.Url.Host != null && request.UrlReferrer.Host != request.Url.Host)
            {
                Daco.Web.CLinkBuilder.AccessDenied();
            }
        }

        public string GetImageUrl(string imageUrl)
        {
            return GetImageUrl(imageUrl, false);
        }

        public string GetImageUrl(string imageUrl, bool useTheme)
        {
            if (useTheme)
            {
                if (imageUrl.IndexOf("~/") >= 0) imageUrl = imageUrl.Replace("~/", "");
                else if (imageUrl[0] == '/') imageUrl = imageUrl.Remove(0);

                return Page.ResolveUrl(string.Format("~/App_Themes/{0}/{1}", Config.CSiteConfig.Current.Theme, imageUrl));
            }
            else
                return Page.ResolveUrl(imageUrl);
        }

        public string GetPageUrl(string pageUrl)
        {
            string strBaseUrl = string.Empty; // CUrlBuilder.Path;

            if (pageUrl.IndexOf("~/") >= 0) pageUrl = pageUrl.Replace("~/", "");
            else if (pageUrl[0] == '/') pageUrl = pageUrl.Remove(0);

            //return string.Format("http://localhost{0}{1}", strBaseUrl, pageUrl);
            return string.Format("http://{2}{0}/{1}", Request.ApplicationPath, pageUrl, Request.Url.Host);
        }

        protected void RegisterCss(string href)
        {
            System.Web.UI.HtmlControls.HtmlLink gridCss = new System.Web.UI.HtmlControls.HtmlLink();
            gridCss.Attributes["type"] = "text/css";
            gridCss.Attributes["rel"] = "Stylesheet";

            if (href.IndexOf("~/") >= 0) href = href.Replace("~/", "");
            else if (href[0] == '/') href = href.Remove(0);

            gridCss.Href = string.Format("~/App_Themes/{0}/{1}", Config.CSiteConfig.Current.Theme, href);
            Page.Header.Controls.Add(gridCss);
        }

        protected void RegisterCss(string href, bool useTheme)
        {
            if (useTheme) RegisterCss(href);
            else
            {
                System.Web.UI.HtmlControls.HtmlLink gridCss = new System.Web.UI.HtmlControls.HtmlLink();
                gridCss.Attributes["type"] = "text/css";
                gridCss.Attributes["rel"] = "Stylesheet";

                if (href.IndexOf("~/") >= 0) href = href.Replace("~/", "");
                else if (href[0] == '/') href = href.Remove(0);

                gridCss.Href = string.Format("~/{0}", href);
                Page.Header.Controls.Add(gridCss);
            }
        }

        public class DACOBody : Control
        {
            private DACOLeft _left = null;
            public DACOLeft Left
            {
                get { return _left; }
                protected set { _left = value; }
            }

            private DACORight _right = null;
            public DACORight Right
            {
                get { return _right; }
                protected set { _right = value; }
            }

            public DACOBody()
            {
                Left = new DACOLeft();
                Right = new DACORight();

                this.Load += new EventHandler(DACOBody_Load);
            }

            void DACOBody_Load(object sender, EventArgs e)
            {
                Controls.Add(Left);
                Controls.Add(Right);
            }

            protected override void Render(HtmlTextWriter writer)
            {
                writer.WriteLine(@"
                    <div style=""margin: 0; min-height: 250px;"">
                        <div style=""margin: 5px;"">
                ");
                base.Render(writer);
                writer.WriteLine(@"
                        </div>
                    </div>
                    <div class=""DIVClear"" />
                ");
            }
        }

        public class DACOLeft : Control
        {
            public DACOLeft()
            {
                this.Load += new EventHandler(DACOLeft_Load);
            }

            void DACOLeft_Load(object sender, EventArgs e)
            {

            }

            protected override void Render(HtmlTextWriter writer)
            {
                writer.WriteLine(@"
                    <!-- Begin left -->
                    <div id=""left"">
                ");
                base.Render(writer);
                writer.WriteLine(@"
                    </div>
                    <!-- End left -->
                ");
            }
        }

        public class DACORight : Control
        {
            public DACORight()
            {
                this.Load += new EventHandler(DACORight_Load);
            }

            void DACORight_Load(object sender, EventArgs e)
            {

            }

            protected override void Render(HtmlTextWriter writer)
            {
                writer.WriteLine(@"
                <!-- Begin right -->
                    <div id=""middle"">
                        <div style=""margin-left: 5px;"">
                ");
                base.Render(writer);
                writer.WriteLine(@"
                        </div>
                    </div>
                ");
            }
        }
    }
}
